/*
 * @Author: lbr
 * @Date: 2019-09-03 17:01:36
 * @Description: file content
 */
import axios from 'axios'
import qs from 'qs';

const ROOT = process.env.VUE_APP_ROOT
import {
  myLocalStorage,
} from '@/uilts/uilts'
import {Loading, Message} from 'element-ui';

let loadingInstance = ''
axios.defaults.timeout = 10000;
axios.interceptors.request.use(
    config => {
      const token = myLocalStorage.get('token');
      token && (config.headers.authorization = token);
      if (config.method === 'get') {
        // config.params=qs.stringify(config.params,{ arrayFormat: 'indices' })
      } else if (config.method === 'post') {
        // config.data = qs.stringify(config.data);
        // config.headers['Content-Type'] = 'application/json';
      }
      return config;
    },
    err => {
      return Promise.reject(err);
    });


function ajaxContent(params, res) {
  // 登录状态已失效
  if (res.code === 3000) {
    myLocalStorage.remove("token");
    window.location.replace('/login');
    return;
  }
  if (params.loading) {
    loadingInstance.close();
  }
}

//封装Promise
export default params => {
  if (params.loading) {
    loadingInstance = Loading.service({fullscreen: true});
  }
  return new Promise((resolve, reject) => {
    const data = params.method === 'post' ? {data: params.data} : {params: params.data}
    axios.request({
      baseURL: params.baseURL || ROOT,
      url: params.url,
      method: params.method || 'get',
      ...data,
    }).then(res => {
      ajaxContent(params, res.data);
      if (res.data.code === 200) {
        resolve(res.data);
      } else {
        reject(res.data.msg)
      }
    }).catch((error) => {
      reject(error)
      if (params.loading) {
        loadingInstance.close();
      }
    });
  }).catch((err) => {
    const hintErr = params.hintErr || false; //禁止弹出警告提示 true: 不弹出    默认弹出
    if (!hintErr) {
      Message({
        message: err,
        type: 'error'
      });
    }
  })
};
